package com.yuezhi.producer.controller;

import com.yuezhi.producer.constant.QueueConstant;
import com.yuezhi.producer.entity.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.PublisherCallbackChannel;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RpcClientController {

    private static final Logger logger = LoggerFactory.getLogger(RpcClientController.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Student student;
    /**
     * 消息发送
     * @param msg 消息
     */
    @GetMapping("/send")
    public Student send(String msg) {
        // 创建消息对象
        Message message = MessageBuilder.withBody(msg.getBytes()).build();
        Message sendAndReceive = rabbitTemplate.sendAndReceive(QueueConstant.RPC_EXCHANGE, QueueConstant.RPC_QUEUE_ONE, message);
        if (sendAndReceive != null) {
            // 获取已发送的消息的correlationId
            String correlationId = message.getMessageProperties().getCorrelationId();
            logger.info("correlationId:{}",correlationId);
            // 获取响应头信息
            Map<String, Object> headers = sendAndReceive.getMessageProperties().getHeaders();
           if (headers != null) {
               // 获取server返回的消息id
               String msgId = (String)headers.get(PublisherCallbackChannel.RETURNED_MESSAGE_CORRELATION_KEY);
               if(msgId.equals(correlationId)) {
                   String s = new String(sendAndReceive.getBody());
                   logger.info("服务端处理后的消息:{}", s);
                   student.setRemark(s);
                   return student;
               }
           }
        }
        return student;
    }
}
